<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>登录 / 注册</title>
</head>
<body>
  <div class="container" id="login-form">
    <h1>登录页</h1>
    <form id="loginForm">
      <div class="form-group">
        <label for="username">用户名：</label>
        <input type="text" id="username" name="username" required>
      </div>
      <div class="form-group">
        <label for="password">密码：</label>
        <input type="password" id="password" name="password" required>
      </div>
      <button type="submit">登录</button>
      <p id="errorMessage" style="color: red;"></p>
    </form>
    <p>没有账户？ <a href="#" onclick="showRegisterForm()">请注册</a></p>
  </div>

  <div class="container" id="register-form" style="display:none;">
    <h1>注册页</h1>
    <form action="/register" method="POST">
      <div class="form-group">
        <label for="reg-username">用户名：</label>
        <input type="text" id="reg-username" name="username" required>
      </div>
      <div class="form-group">
        <label for="reg-password">密码：</label>
        <input type="password" id="reg-password" name="password" required>
      </div>
      <div class="form-group">
        <label for="usertype">用户类型：</label>
        <select id="usertype" name="usertype" required>
            <option value="student">学生</option>
            <option value="teacher">老师</option>
            <option value="admin">管理员</option>
        </select>
      </div>
      <button type="submit">注册</button>
    </form>
    <p>已有账户？ <a href="#" onclick="showLoginForm()">请登录</a></p>
  </div>

  <script>
    function showRegisterForm() {
      document.getElementById('login-form').style.display = 'none';
      document.getElementById('register-form').style.display = 'block';
    }

    function showLoginForm() {
      document.getElementById('register-form').style.display = 'none';
      document.getElementById('login-form').style.display = 'block';
    }

    document.getElementById('loginForm').addEventListener('submit', function(event) {
      event.preventDefault();

      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;

      fetch('/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `username=${username}&password=${password}`
      })
      .then(response => {
        if (response.redirected) {
          window.location.href = response.url;
        } else if (response.status === 401) {
          return response.text().then(text => { throw new Error(text) });
        }
      })
      .catch(error => {
        document.getElementById('errorMessage').textContent = error.message;
      });
    });
  </script>
</body>
</html>
